<?php
include 'header.php';
?>

<style>
    /* 链接管理页面样式 */
    .panel-header-content {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 20px;
    }

    .links-container {
        display: grid;
        gap: 16px;
    }

    .link-card {
        background: var(--white);
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius-lg);
        padding: 20px;
        transition: all 0.2s ease;
        cursor: move;
        cursor: grab;
        user-select: none;
    }

    .link-card:hover {
        border-color: var(--primary-blue);
        box-shadow: var(--shadow);
        transform: translateY(-1px);
    }

    .link-card.dragging {
        opacity: 0.5;
        cursor: grabbing;
        transform: scale(0.98);
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
        border: 2px dashed var(--primary-blue);
        background: #f8f9fa;
    }

    .link-card.drag-over::before {
        content: '';
        position: absolute;
        top: -6px;
        left: 0;
        right: 0;
        height: 4px;
        background: var(--primary-blue);
        border-radius: 2px;
        box-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
        animation: pulse 0.6s ease-in-out infinite;
        z-index: 10;
    }

    .link-card.drag-over::after {
        content: '放置到这里';
        position: absolute;
        top: -28px;
        left: 50%;
        transform: translateX(-50%);
        background: var(--primary-blue);
        color: white;
        padding: 4px 12px;
        border-radius: 4px;
        font-size: 0.85rem;
        font-weight: 500;
        white-space: nowrap;
        box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
        z-index: 11;
    }

    @keyframes pulse {
        0%, 100% {
            opacity: 1;
            transform: scaleY(1);
        }
        50% {
            opacity: 0.7;
            transform: scaleY(1.2);
        }
    }

    .drag-handle {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 24px;
        color: var(--gray-400);
        cursor: grab;
        flex-shrink: 0;
        margin-right: 8px;
        transition: all 0.2s ease;
        touch-action: none;
    }

    .drag-handle:hover {
        color: var(--primary-blue);
        transform: scale(1.1);
    }

    .drag-handle:active {
        cursor: grabbing;
        color: var(--primary-blue);
    }

    /* 拖动占位符 */
    .drag-placeholder {
        background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
        border: 2px dashed var(--primary-blue);
        border-radius: 12px;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--primary-blue);
        font-size: 0.9rem;
        font-weight: 500;
        transition: all 0.2s ease;
    }

    .link-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 12px;
    }

    .link-info {
        flex: 1;
        min-width: 0;
    }

    .link-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: var(--gray-900);
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        gap: 8px;
        flex-wrap: wrap;
    }

    .link-title > i:not(.fa-grip-vertical) {
        color: var(--primary-blue);
        width: 16px;
        text-align: center;
    }

    .link-url {
        color: var(--primary-blue);
        text-decoration: none;
        font-size: 0.9rem;
        word-break: break-all;
        display: block;
        margin-bottom: 8px;
    }

    .link-url:hover {
        text-decoration: underline;
    }

    .link-description {
        color: var(--gray-600);
        font-size: 0.9rem;
        line-height: 1.5;
    }

    .link-actions {
        display: flex;
        gap: 8px;
        flex-shrink: 0;
    }

    .link-stats {
        display: flex;
        align-items: center;
        gap: 16px;
        padding-top: 12px;
        border-top: 1px solid var(--gray-100);
        font-size: 0.85rem;
        color: var(--gray-600);
    }

    .link-clicks {
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .link-clicks i {
        color: var(--primary-blue);
    }

    /* 空状态 */
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: var(--gray-500);
    }

    .empty-state i {
        font-size: 4rem;
        margin-bottom: 20px;
        color: var(--gray-300);
    }

    .empty-state h3 {
        font-size: 1.5rem;
        margin: 0 0 12px 0;
        color: var(--gray-700);
    }

    .empty-state p {
        margin: 0 0 24px 0;
        font-size: 1rem;
    }

    /* 按钮样式 */
    .btn {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 8px 16px;
        border: none;
        border-radius: var(--border-radius);
        font-size: 0.9rem;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        text-decoration: none;
        justify-content: center;
    }

    .btn-sm {
        padding: 6px 12px;
        font-size: 0.8rem;
    }

    .btn-primary {
        background: var(--primary-blue);
        color: var(--white);
    }

    .btn-primary:hover {
        background: var(--primary-blue-dark);
        transform: translateY(-1px);
        box-shadow: var(--shadow);
    }

    .btn-secondary {
        background: var(--gray-200);
        color: var(--gray-700);
    }

    .btn-secondary:hover {
        background: var(--gray-300);
        color: var(--gray-800);
    }

    .btn-danger {
        background: var(--error-red);
        color: var(--white);
    }

    .btn-danger:hover {
        background: #b91c1c;
        transform: translateY(-1px);
        box-shadow: var(--shadow);
    }

    /* 模态框样式 */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1000;
        align-items: center;
        justify-content: center;
    }

    .modal-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(4px);
        -webkit-backdrop-filter: blur(4px);
        transition: opacity 0.3s ease-out;
    }

    .modal-content {
        background: var(--white);
        border-radius: var(--border-radius-lg);
        padding: 32px;
        width: 90%;
        max-width: 500px;
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: var(--shadow-xl);
        transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
        will-change: transform, opacity;
        position: relative;
        z-index: 10;
    }

    .modal-header {
        margin-bottom: 24px;
    }

    .modal-title {
        font-size: 1.5rem;
        font-weight: 700;
        color: var(--gray-900);
        margin: 0;
    }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        margin-top: 24px;
        padding-top: 24px;
        border-top: 1px solid var(--gray-200);
    }

    /* 表单样式 */
    .form-grid {
        display: grid;
        gap: 20px;
    }

    .form-group {
        display: flex;
        flex-direction: column;
    }

    .form-label {
        font-size: 0.9rem;
        font-weight: 600;
        color: var(--gray-700);
        margin-bottom: 8px;
    }

    .form-input,
    .form-textarea {
        padding: 12px 16px;
        border: 1px solid var(--gray-300);
        border-radius: var(--border-radius);
        font-size: 0.95rem;
        transition: all 0.2s ease;
        background: var(--white);
    }

    .form-input:focus,
    .form-textarea:focus {
        outline: none;
        border-color: var(--primary-blue);
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
    }

    .form-textarea {
        min-height: 80px;
        resize: vertical;
        font-family: inherit;
    }

    /* 移动端优化 */
    @media (max-width: 768px) {
        .panel-header-content {
            flex-direction: column;
            align-items: stretch;
        }

        .link-header {
            flex-direction: column;
            gap: 12px;
        }

        .link-actions {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            width: 100%;
        }

        .link-actions .btn {
            width: 100%;
            justify-content: center;
            padding: 10px 16px;
        }

        .modal-content {
            width: 95%;
            margin: 16px;
            padding: 20px;
            border-radius: 12px;
            max-height: 90vh;
        }

        .modal-header {
            margin-bottom: 16px;
        }

        .modal-title {
            font-size: 1.3rem;
        }

        .modal-footer {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 16px;
            padding-top: 16px;
        }

        .modal-footer .btn {
            width: 100%;
            justify-content: center;
            padding: 10px 16px;
        }
    }

    @media (max-width: 480px) {
        .modal-content {
            width: 98%;
            margin: 8px;
            padding: 16px;
        }
    }
</style>

<!-- 页面内容 -->
<div class="panel">
    <div class="panel-header">
        <div class="panel-header-content">
            <div>
                <h2 class="panel-title">链接管理</h2>
                <p class="panel-subtitle">管理您的导航链接</p>
            </div>
            <button class="btn btn-primary" onclick="showAddModal(event)">
                <i class="fas fa-plus"></i>
                添加链接
            </button>
        </div>
    </div>
    <div class="panel-content">
        <div class="links-container" id="links-container">
            <?php if (empty($Data)): ?>
                <div class="empty-state">
                    <i class="fas fa-link"></i>
                    <h3>暂无链接</h3>
                    <p>您还没有添加任何导航链接</p>
                    <button class="btn btn-primary" onclick="showAddModal(event)">
                        <i class="fas fa-plus"></i>
                        添加第一个链接
                    </button>
                </div>
            <?php else: ?>
                <?php foreach ($Data as $index => $link): ?>
                    <div class="link-card" data-index="<?php echo $index; ?>" draggable="true">
                        <div class="link-header">
                            <div class="link-info">
                                <div class="link-title">
                                    <span class="drag-handle" title="拖动排序">
                                        <i class="fas fa-grip-vertical"></i>
                                    </span>
                                    <i class="<?php echo htmlspecialchars($link['icon'] ?? 'fas fa-link'); ?>"></i>
                                    <?php echo htmlspecialchars($link['title']); ?>
                                </div>
                                <a href="<?php echo htmlspecialchars($link['url']); ?>" target="_blank" class="link-url">
                                    <?php echo htmlspecialchars($link['url']); ?>
                                </a>
                                <?php if (!empty($link['description'])): ?>
                                    <div class="link-description">
                                        <?php echo htmlspecialchars($link['description']); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="link-actions">
                                <button class="btn btn-sm btn-secondary" onclick="editLink(<?php echo $index; ?>, event)">
                                    <i class="fas fa-edit"></i>
                                    编辑
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deleteLink(<?php echo $index; ?>)">
                                    <i class="fas fa-trash"></i>
                                    删除
                                </button>
                            </div>
                        </div>
                        <div class="link-stats">
                            <span class="link-clicks">
                                <i class="fas fa-mouse-pointer"></i>
                                点击次数: <?php echo intval($link['clicks'] ?? 0); ?>
                            </span>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- 编辑链接模态框 -->
<div class="modal" id="edit-modal">
    <div class="modal-overlay"></div>
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">编辑链接</h3>
        </div>
        <form id="edit-link-form">
            <input type="hidden" id="edit_link_index" name="link_index">
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label" for="edit_link_title">链接标题 *</label>
                    <input type="text" id="edit_link_title" name="link_title" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="edit_link_url">链接地址 *</label>
                    <input type="url" id="edit_link_url" name="link_url" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="edit_link_icon">图标类名或图片URL</label>
                    <div style="display: flex; gap: 8px;">
                        <input type="text" id="edit_link_icon" name="link_icon" class="form-input" placeholder="例如：fas fa-home 或 https://xxx.com/icon.png" style="flex: 1;">
                        <label for="edit_icon_upload" class="btn btn-sm btn-secondary" style="margin: 0; cursor: pointer; white-space: nowrap;">
                            <i class="fas fa-upload"></i> 上传
                        </label>
                        <input type="file" id="edit_icon_upload" accept=".jpg,.jpeg,.png,.gif,.webp,.svg,.ico" style="display: none;">
                    </div>
                    <small style="color: var(--gray-600); font-size: 0.85rem; margin-top: 4px; display: block;">支持 Font Awesome 图标类名、图片URL 或上传图片（JPG、PNG、GIF、SVG、ICO，最大2MB）</small>
                </div>
                <div class="form-group">
                    <label class="form-label" for="edit_link_description">链接描述</label>
                    <textarea id="edit_link_description" name="link_description" class="form-textarea" placeholder="简要描述这个链接..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i>
                    保存修改
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 添加链接模态框 -->
<div class="modal" id="add-modal">
    <div class="modal-overlay"></div>
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">添加新链接</h3>
        </div>
        <form id="add-link-form">
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label" for="add_link_title">链接标题 *</label>
                    <input type="text" id="add_link_title" name="link_title" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="add_link_url">链接地址 *</label>
                    <input type="url" id="add_link_url" name="link_url" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="add_link_icon">图标类名或图片URL</label>
                    <div style="display: flex; gap: 8px;">
                        <input type="text" id="add_link_icon" name="link_icon" class="form-input" placeholder="例如：fas fa-home 或 https://xxx.com/icon.png" style="flex: 1;">
                        <label for="add_icon_upload" class="btn btn-sm btn-secondary" style="margin: 0; cursor: pointer; white-space: nowrap;">
                            <i class="fas fa-upload"></i> 上传
                        </label>
                        <input type="file" id="add_icon_upload" accept=".jpg,.jpeg,.png,.gif,.webp,.svg,.ico" style="display: none;">
                    </div>
                    <small style="color: var(--gray-600); font-size: 0.85rem; margin-top: 4px; display: block;">支持 Font Awesome 图标类名、图片URL 或上传图片（JPG、PNG、GIF、SVG、ICO，最大2MB）</small>
                </div>
                <div class="form-group">
                    <label class="form-label" for="add_link_description">链接描述</label>
                    <textarea id="add_link_description" name="link_description" class="form-textarea" placeholder="简要描述这个链接..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeAddModal()">取消</button>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-plus"></i>
                    添加链接
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // 全局变量
    let linksData = <?php echo json_encode($Data); ?>;
    let dragSrcElement = null;
    let dragStartIndex = null;

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 绑定模态框点击外部关闭事件
        document.getElementById('edit-modal').addEventListener('click', function(e) {
            if (e.target === this || e.target.classList.contains('modal-overlay')) {
                closeModal();
            }
        });

        document.getElementById('add-modal').addEventListener('click', function(e) {
            if (e.target === this || e.target.classList.contains('modal-overlay')) {
                closeAddModal();
            }
        });

        // 绑定表单提交事件
        document.getElementById('edit-link-form').addEventListener('submit', handleEditSubmit);
        document.getElementById('add-link-form').addEventListener('submit', handleAddSubmit);

        // 绑定图标上传事件
        document.getElementById('edit_icon_upload').addEventListener('change', function() {
            uploadIcon(this, 'edit');
        });
        document.getElementById('add_icon_upload').addEventListener('change', function() {
            uploadIcon(this, 'add');
        });

        // ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const editModal = document.getElementById('edit-modal');
                const addModal = document.getElementById('add-modal');
                if (editModal.style.display === 'flex') {
                    closeModal();
                } else if (addModal.style.display === 'flex') {
                    closeAddModal();
                }
            }
        });

        // 初始化拖动排序
        initDragAndDrop();
    });

    // 保存当前触发弹窗的按钮位置
    let currentTriggerRect = null;

    // 显示添加链接弹窗
    function showAddModal(event) {
        const modal = document.getElementById('add-modal');
        const modalContent = modal.querySelector('.modal-content');
        const modalOverlay = modal.querySelector('.modal-overlay');

        // 获取触发按钮的位置
        let triggerElement = event ? event.target : null;
        if (triggerElement && triggerElement.tagName !== 'BUTTON') {
            triggerElement = triggerElement.closest('button');
        }

        if (triggerElement) {
            currentTriggerRect = triggerElement.getBoundingClientRect();

            // 先显示模态框
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden'; // 防止背景滚动

            // 设置遮罩层初始状态
            modalOverlay.style.opacity = '0';

            // 设置弹窗内容初始状态：从按钮位置开始
            modalContent.style.transform = `translate(${currentTriggerRect.left + currentTriggerRect.width / 2 - window.innerWidth / 2}px, ${currentTriggerRect.top + currentTriggerRect.height / 2 - window.innerHeight / 2}px) scale(0.1)`;
            modalContent.style.opacity = '0';

            // 强制重排，确保初始样式生效
            modalContent.offsetHeight;

            // 使用 requestAnimationFrame 确保动画流畅
            requestAnimationFrame(() => {
                // 遮罩层淡入
                modalOverlay.style.opacity = '1';
                // 弹窗内容动画到最终位置
                modalContent.style.transform = 'translate(0, 0) scale(1)';
                modalContent.style.opacity = '1';
            });
        } else {
            // 没有触发元素信息，直接显示
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
    }

    // 关闭添加链接弹窗
    function closeAddModal() {
        const modal = document.getElementById('add-modal');
        const modalContent = modal.querySelector('.modal-content');
        const modalOverlay = modal.querySelector('.modal-overlay');

        if (currentTriggerRect) {
            // 遮罩层淡出
            modalOverlay.style.opacity = '0';

            // 弹窗内容动画回到按钮位置
            modalContent.style.transform = `translate(${currentTriggerRect.left + currentTriggerRect.width / 2 - window.innerWidth / 2}px, ${currentTriggerRect.top + currentTriggerRect.height / 2 - window.innerHeight / 2}px) scale(0.1)`;
            modalContent.style.opacity = '0';

            // 等待动画完成后再隐藏
            setTimeout(() => {
                modal.style.display = 'none';
                document.body.style.overflow = ''; // 恢复背景滚动
                // 重置样式
                modalContent.style.transform = '';
                modalContent.style.opacity = '';
                modalOverlay.style.opacity = '';
                resetAddLinkForm();
                currentTriggerRect = null;
            }, 400); // 与CSS transition时间一致
        } else {
            // 直接关闭
            modal.style.display = 'none';
            document.body.style.overflow = '';
            resetAddLinkForm();
        }
    }

    // 重置添加链接表单
    function resetAddLinkForm() {
        document.getElementById('add-link-form').reset();
    }

    // 编辑链接
    function editLink(index, event) {
        const link = linksData[index];
        if (!link) return;

        // 填充表单数据
        document.getElementById('edit_link_index').value = index;
        document.getElementById('edit_link_title').value = link.title || '';
        document.getElementById('edit_link_url').value = link.url || '';
        document.getElementById('edit_link_icon').value = link.icon || '';
        document.getElementById('edit_link_description').value = link.description || '';

        // 显示模态框，带动画效果
        const modal = document.getElementById('edit-modal');
        const modalContent = modal.querySelector('.modal-content');
        const modalOverlay = modal.querySelector('.modal-overlay');

        // 获取触发按钮或卡片的位置
        let triggerElement = event ? event.target : null;
        if (triggerElement) {
            if (triggerElement.tagName !== 'BUTTON') {
                triggerElement = triggerElement.closest('button');
            }
            if (!triggerElement) {
                triggerElement = document.querySelector(`.link-card[data-index="${index}"]`);
            }
        } else {
            triggerElement = document.querySelector(`.link-card[data-index="${index}"]`);
        }

        if (triggerElement) {
            currentTriggerRect = triggerElement.getBoundingClientRect();

            // 先显示模态框
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden'; // 防止背景滚动

            // 设置遮罩层初始状态
            modalOverlay.style.opacity = '0';

            // 设置弹窗内容初始状态：从卡片/按钮位置开始
            modalContent.style.transform = `translate(${currentTriggerRect.left + currentTriggerRect.width / 2 - window.innerWidth / 2}px, ${currentTriggerRect.top + currentTriggerRect.height / 2 - window.innerHeight / 2}px) scale(0.1)`;
            modalContent.style.opacity = '0';

            // 强制重排，确保初始样式生效
            modalContent.offsetHeight;

            // 使用 requestAnimationFrame 确保动画流畅
            requestAnimationFrame(() => {
                // 遮罩层淡入
                modalOverlay.style.opacity = '1';
                // 弹窗内容动画到最终位置
                modalContent.style.transform = 'translate(0, 0) scale(1)';
                modalContent.style.opacity = '1';
            });
        } else {
            // 没有触发元素信息，直接显示
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
    }

    // 删除链接
    async function deleteLink(index) {
        const link = linksData[index];
        if (!link) return;

        if (!confirm(`确定要删除链接"${link.title}"吗？`)) {
            return;
        }

        try {
            const response = await fetch('api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'deleteLink',
                    index: index
                })
            });

            const data = await response.json();

            if (data.success) {
                AntMessage.success(data.message || '链接删除成功');
                // 更新本地数据
                linksData.splice(index, 1);
                // 重新渲染链接列表
                renderLinks();
            } else {
                AntMessage.error(data.message || '删除失败，请重试');
            }
        } catch (error) {
            console.error('Error:', error);
            AntMessage.error('网络错误，请检查连接后重试');
        }
    }

    // 关闭编辑模态框
    function closeModal() {
        const modal = document.getElementById('edit-modal');
        const modalContent = modal.querySelector('.modal-content');
        const modalOverlay = modal.querySelector('.modal-overlay');
        
        if (currentTriggerRect) {
            // 遮罩层淡出
            modalOverlay.style.opacity = '0';
            
            // 弹窗内容动画回到原位置
            modalContent.style.transform = `translate(${currentTriggerRect.left + currentTriggerRect.width / 2 - window.innerWidth / 2}px, ${currentTriggerRect.top + currentTriggerRect.height / 2 - window.innerHeight / 2}px) scale(0.1)`;
            modalContent.style.opacity = '0';
            
            // 等待动画完成后再隐藏
            setTimeout(() => {
                modal.style.display = 'none';
                document.body.style.overflow = ''; // 恢复背景滚动
                // 重置样式
                modalContent.style.transform = '';
                modalContent.style.opacity = '';
                modalOverlay.style.opacity = '';
                currentTriggerRect = null;
            }, 400); // 与CSS transition时间一致
        } else {
            // 直接关闭
            modal.style.display = 'none';
            document.body.style.overflow = '';
        }
    }

    // 处理编辑表单提交
    async function handleEditSubmit(e) {
        e.preventDefault();

        const formData = new FormData(e.target);
        const submitBtn = e.target.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        // 显示加载状态
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
        submitBtn.disabled = true;

        try {
            const response = await fetch('api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'updateLink',
                    index: formData.get('link_index'),
                    title: formData.get('link_title'),
                    url: formData.get('link_url'),
                    icon: formData.get('link_icon'),
                    description: formData.get('link_description')
                })
            });

            const data = await response.json();

            if (data.success) {
                AntMessage.success(data.message || '链接修改成功');

                // 更新本地数据
                const index = parseInt(formData.get('link_index'));
                linksData[index] = {
                    ...linksData[index],
                    title: formData.get('link_title'),
                    url: formData.get('link_url'),
                    icon: formData.get('link_icon'),
                    description: formData.get('link_description')
                };

                // 重新渲染链接列表
                renderLinks();
                closeModal();
            } else {
                AntMessage.error(data.message || '修改失败，请重试');
            }
        } catch (error) {
            console.error('Error:', error);
            AntMessage.error('网络错误，请检查连接后重试');
        } finally {
            // 恢复按钮状态
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    // 处理添加表单提交
    async function handleAddSubmit(e) {
        e.preventDefault();

        const formData = new FormData(e.target);
        const submitBtn = e.target.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        // 显示加载状态
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 添加中...';
        submitBtn.disabled = true;

        try {
            const response = await fetch('api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'addLink',
                    title: formData.get('link_title'),
                    url: formData.get('link_url'),
                    icon: formData.get('link_icon'),
                    description: formData.get('link_description')
                })
            });

            const data = await response.json();

            if (data.success) {
                AntMessage.success(data.message || '链接添加成功');

                // 添加到本地数据
                linksData.push({
                    title: formData.get('link_title'),
                    url: formData.get('link_url'),
                    icon: formData.get('link_icon') || 'fas fa-link',
                    description: formData.get('link_description'),
                    clicks: 0
                });

                // 重新渲染链接列表
                renderLinks();
                closeAddModal();
            } else {
                AntMessage.error(data.message || '添加失败，请重试');
            }
        } catch (error) {
            console.error('Error:', error);
            AntMessage.error('网络错误，请检查连接后重试');
        } finally {
            // 恢复按钮状态
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    // 重新渲染链接列表
    function renderLinks() {
        const container = document.getElementById('links-container');

        if (linksData.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-link"></i>
                    <h3>暂无链接</h3>
                    <p>您还没有添加任何导航链接</p>
                    <button class="btn btn-primary" onclick="showAddModal(event)">
                        <i class="fas fa-plus"></i>
                        添加第一个链接
                    </button>
                </div>
            `;
            return;
        }

        container.innerHTML = linksData.map((link, index) => `
            <div class="link-card" data-index="${index}" draggable="false">
                <div class="link-header">
                    <div class="link-info">
                        <div class="link-title">
                            <span class="drag-handle" title="拖动排序">
                                <i class="fas fa-grip-vertical"></i>
                            </span>
                            <i class="${link.icon || 'fas fa-link'}"></i>
                            ${link.title}
                        </div>
                        <a href="${link.url}" target="_blank" class="link-url">
                            ${link.url}
                        </a>
                        ${link.description ? `<div class="link-description">${link.description}</div>` : ''}
                    </div>
                    <div class="link-actions">
                        <button class="btn btn-sm btn-secondary" onclick="editLink(${index}, event)">
                            <i class="fas fa-edit"></i>
                            编辑
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteLink(${index})">
                            <i class="fas fa-trash"></i>
                            删除
                        </button>
                    </div>
                </div>
                <div class="link-stats">
                    <span class="link-clicks">
                        <i class="fas fa-mouse-pointer"></i>
                        点击次数: ${link.clicks || 0}
                    </span>
                </div>
            </div>
        `).join('');

        // 重新初始化拖动排序
        initDragAndDrop();
    }

    // 初始化拖动排序功能（兼容电脑端和手机端）
    function initDragAndDrop() {
        const cards = document.querySelectorAll('.link-card');
        
        cards.forEach(card => {
            // 电脑端：监听鼠标按下事件，只在拖动手柄上允许拖动
            card.addEventListener('mousedown', function(e) {
                if (e.target.closest('.drag-handle')) {
                    card.setAttribute('draggable', 'true');
                } else {
                    card.setAttribute('draggable', 'false');
                }
            });

            // 电脑端拖动事件
            card.addEventListener('dragstart', handleDragStart);
            card.addEventListener('dragend', handleDragEnd);
            card.addEventListener('dragover', handleDragOver);
            card.addEventListener('drop', handleDrop);
            card.addEventListener('dragenter', handleDragEnter);
            card.addEventListener('dragleave', handleDragLeave);

            // 移动端触摸事件
            let touchStartY = 0;
            let touchStartX = 0;
            let isTouching = false;
            let isDragging = false;
            let lastSwapIndex = null;
            let touchMoveThrottle = null;

            card.addEventListener('touchstart', function(e) {
                // 如果点击的是按钮或链接，不触发拖动
                if (e.target.closest('button') || e.target.closest('a')) {
                    return;
                }

                // 只有触摸拖动手柄才能拖动
                if (!e.target.closest('.drag-handle')) {
                    return;
                }

                isTouching = true;
                isDragging = false;
                const touch = e.touches[0];
                touchStartY = touch.clientY;
                touchStartX = touch.clientX;
                dragStartIndex = parseInt(card.dataset.index);
                lastSwapIndex = dragStartIndex;
            }, { passive: true });

            card.addEventListener('touchmove', function(e) {
                if (!isTouching) return;

                const touch = e.touches[0];
                const deltaY = touch.clientY - touchStartY;
                const deltaX = touch.clientX - touchStartX;

                // 如果主要是垂直移动，则进行拖动排序
                if (Math.abs(deltaY) > Math.abs(deltaX) && Math.abs(deltaY) > 15) {
                    if (!isDragging) {
                        isDragging = true;
                        card.classList.add('dragging');
                    }

                    e.preventDefault(); // 防止滚动

                    // 使用节流优化性能
                    if (touchMoveThrottle) {
                        clearTimeout(touchMoveThrottle);
                    }

                    touchMoveThrottle = setTimeout(() => {
                        // 移除所有drag-over样式
                        document.querySelectorAll('.link-card.drag-over').forEach(c => {
                            c.classList.remove('drag-over');
                        });

                        // 获取当前触摸位置的元素
                        const elementBelow = document.elementFromPoint(touch.clientX, touch.clientY);
                        const cardBelow = elementBelow?.closest('.link-card');

                        if (cardBelow && cardBelow !== card) {
                            const cardBelowIndex = parseInt(cardBelow.dataset.index);
                            const cardIndex = parseInt(card.dataset.index);

                            // 添加目标位置提示
                            cardBelow.classList.add('drag-over');

                            // 交换位置（减少不必要的渲染）
                            if (cardBelowIndex !== cardIndex && cardBelowIndex !== lastSwapIndex) {
                                lastSwapIndex = cardBelowIndex;
                                swapArrayElements(linksData, cardIndex, cardBelowIndex);
                                renderLinks();
                            }
                        }
                    }, 50); // 50ms节流
                }
            }, { passive: false });

            card.addEventListener('touchend', function(e) {
                if (!isTouching) return;

                isTouching = false;
                isDragging = false;
                card.classList.remove('dragging');
                
                // 清除节流定时器
                if (touchMoveThrottle) {
                    clearTimeout(touchMoveThrottle);
                    touchMoveThrottle = null;
                }

                // 移除所有drag-over样式
                document.querySelectorAll('.link-card.drag-over').forEach(c => {
                    c.classList.remove('drag-over');
                });

                // 保存新的排序
                if (dragStartIndex !== null && lastSwapIndex !== dragStartIndex) {
                    saveOrder();
                }
                
                dragStartIndex = null;
                lastSwapIndex = null;
            }, { passive: true });

            // 取消触摸时清理
            card.addEventListener('touchcancel', function(e) {
                isTouching = false;
                isDragging = false;
                card.classList.remove('dragging');
                
                if (touchMoveThrottle) {
                    clearTimeout(touchMoveThrottle);
                    touchMoveThrottle = null;
                }

                document.querySelectorAll('.link-card.drag-over').forEach(c => {
                    c.classList.remove('drag-over');
                });
                
                dragStartIndex = null;
                lastSwapIndex = null;
            }, { passive: true });
        });
    }

    // 拖动开始（电脑端）
    function handleDragStart(e) {
        // 如果卡片不可拖动，阻止
        if (this.getAttribute('draggable') !== 'true') {
            e.preventDefault();
            return;
        }

        dragSrcElement = this;
        dragStartIndex = parseInt(this.dataset.index);
        
        this.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', this.innerHTML);
    }

    // 拖动结束（电脑端）
    function handleDragEnd(e) {
        this.classList.remove('dragging');
        
        // 移除所有拖动样式
        document.querySelectorAll('.link-card').forEach(card => {
            card.classList.remove('drag-over');
        });

        // 重置拖动状态（保存操作已在 handleDrop 中完成）
        dragStartIndex = null;
        dragSrcElement = null;
    }

    // 拖动经过（电脑端）
    function handleDragOver(e) {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
        
        if (this === dragSrcElement) {
            return false;
        }

        // 移除其他元素的drag-over类
        document.querySelectorAll('.link-card.drag-over').forEach(card => {
            if (card !== this) {
                card.classList.remove('drag-over');
            }
        });

        // 添加当前元素的drag-over类
        this.classList.add('drag-over');
        
        return false;
    }

    // 拖动进入（电脑端）
    function handleDragEnter(e) {
        e.preventDefault();
        if (this !== dragSrcElement) {
            // 移除其他元素的样式
            document.querySelectorAll('.link-card.drag-over').forEach(card => {
                if (card !== this) {
                    card.classList.remove('drag-over');
                }
            });
            this.classList.add('drag-over');
        }
    }

    // 拖动离开（电脑端）
    function handleDragLeave(e) {
        // 只有当鼠标真正离开元素时才移除样式
        const rect = this.getBoundingClientRect();
        const x = e.clientX;
        const y = e.clientY;
        
        if (x < rect.left || x >= rect.right || y < rect.top || y >= rect.bottom) {
            this.classList.remove('drag-over');
        }
    }

    // 放置（电脑端）
    function handleDrop(e) {
        e.preventDefault();
        e.stopPropagation();

        this.classList.remove('drag-over');

        if (dragSrcElement && dragSrcElement !== this) {
            const dragIndex = parseInt(dragSrcElement.dataset.index);
            const dropIndex = parseInt(this.dataset.index);

            if (dragIndex !== dropIndex) {
                // 交换数组中的元素
                swapArrayElements(linksData, dragIndex, dropIndex);

                // 重新渲染
                renderLinks();

                // 立即保存新的排序
                saveOrder();
            }
        }

        return false;
    }

    // 交换数组元素
    function swapArrayElements(arr, index1, index2) {
        const temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
    }

    // 保存排序到服务器
    async function saveOrder() {
        try {
            const response = await fetch('api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'reorderLinks',
                    links: linksData
                })
            });

            const data = await response.json();

            if (data.success) {
                AntMessage.success('排序已保存');
            } else {
                AntMessage.error(data.message || '保存排序失败');
            }
        } catch (error) {
            console.error('Error:', error);
            AntMessage.error('网络错误，请检查连接后重试');
        }
    }

    // 上传图标
    async function uploadIcon(input, formType) {
        console.log('uploadIcon called, formType:', formType);
        const file = input.files[0];
        if (!file) {
            console.log('No file selected');
            return;
        }

        console.log('File selected:', file.name, 'Size:', file.size, 'Type:', file.type);

        // 验证文件大小（2MB）
        const maxSize = 2 * 1024 * 1024;
        if (file.size > maxSize) {
            AntMessage.error('文件大小不能超过 2MB');
            input.value = '';
            return;
        }

        // 验证文件类型
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml', 'image/x-icon'];
        if (!allowedTypes.includes(file.type)) {
            const ext = file.name.split('.').pop().toLowerCase();
            if (!['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico'].includes(ext)) {
                AntMessage.error('不支持的文件类型，仅支持 JPG、PNG、GIF、WEBP、SVG、ICO 格式');
                input.value = '';
                return;
            }
        }

        // 显示上传中提示
        AntMessage.info('正在上传图标...', 1000);

        try {
            const formData = new FormData();
            formData.append('icon', file);
            formData.append('action', 'uploadIcon');

            console.log('Uploading to api.php...');

            const response = await fetch('api.php', {
                method: 'POST',
                body: formData
            });

            console.log('Response status:', response.status);
            const data = await response.json();
            console.log('Response data:', data);

            if (data.success) {
                // 将上传的图片URL填入图标输入框
                const iconInput = document.getElementById(formType + '_link_icon');
                if (iconInput) {
                    iconInput.value = data.data.url;
                }
                AntMessage.success('图标上传成功');
            } else {
                AntMessage.error(data.message || '上传失败，请重试');
            }
        } catch (error) {
            console.error('Upload error:', error);
            AntMessage.error('上传失败，请检查网络连接');
        } finally {
            // 清空文件input，允许重复上传同一文件
            input.value = '';
        }
    }
</script>

<?php include 'footer.php'; ?>